﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tenta_v2
{
    public class HT<TKey, TValue> : IEnumerable<TValue> where TValue : class
    {
        private Node<TKey, TValue>[] table;

        public HT(int size = 97)
        {
            table = new Node<TKey, TValue>[size];
            for (int i = 0; i < size; i++)
            {
                table[i] = null;
            }
        }

        public void Add(TKey key, TValue value)
        {
            int index = key.GetHashCode() % table.Count();
            if (index < 0)
                index = -index;
            if (table[index] == null)
                table[index] = new Node<TKey, TValue>(key, value);
            else
            {
                Node<TKey, TValue> n = table[index];
                while (n.Next != null)
                    n = n.Next;
                n.Next = new Node<TKey, TValue>(key, value);
            }
        }

        public void Print()
        {
            for (int i = 0; i < table.Count(); i++)
            {
                if (table[i] != null)
                {
                    Console.Write(string.Format("{0,4}", i) + ": ");
                    table[i].Print();
                    Console.WriteLine();
                }
            }
        }

        public Node<TKey, TValue> Search(TKey key)
        {
            int index = key.GetHashCode() % table.Count();
            if (index < 0)
                index = -index;
            Node<TKey, TValue> n = table[index];
            while (n != null)
            {
                if (n.Key.Equals(key))
                    return n;
                else
                    n = n.Next;
            }
            return null;
        }

        public IEnumerator<TValue> GetEnumerator()
        {
            for (int i = 0; i < table.Count(); i++)
            {
                Node<TKey, TValue> n = table[i];
                while (n != null)
                {
                    yield return n.Data;
                    n = n.Next;
                }
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
